function openUrlAndExecScript(url, script, resolve = null) {
  return new Promise((mainResolve, mainReject) => {
    chrome.tabs.create({ url: url, active: true }, function(tab) {
      cacheTab(tab)

      let scriptInjected = false;

      const tabUpdateListener = function(updatedTabId, changeInfo) {
        if (updatedTabId === tab.id && changeInfo.status === 'complete' && !scriptInjected) {
          scriptInjected = true;
          chrome.scripting.executeScript({
            target: { tabId: tab.id },
            files: [script]
          }).then(() => {
            if (resolve !== null) {
              // 设置一个标志或调用resolve函数
            }
            chrome.tabs.onUpdated.removeListener(tabUpdateListener);
            mainResolve(); // 解析主Promise
          }).catch(error => {
            mainReject(error); // 拒绝主Promise
          });
        }
      };

      chrome.tabs.onUpdated.addListener(tabUpdateListener);

      const messageListener = (message, sender) => {
        if (sender.tab.id === tab.id) {
          if (message.action != 'openUrlAndExecScript') return;

          chrome.runtime.onMessage.removeListener(messageListener);
          if (message.data === 'retry') {
            openUrlAndExecScript(url, script, resolve);
          } else if (message.data === 'close page') {
            chrome.tabs.remove(tab.id, ()=>{if (chrome.runtime.lastError);});
            return;
          } else if (resolve !== null) {
            resolve(message.data);
            chrome.tabs.remove(tab.id);
          }
          mainResolve(); // 确保主Promise在所有情况下都会解析
        }
      };

      chrome.runtime.onMessage.addListener(messageListener);
    });
  });
}

function cacheTab(tab) {
  const now = Date.now();
  const tabInfo = { id: tab.id, openedAt: now };

  chrome.storage.local.get(['tabs'], function(result) {
    let tabs = result.tabs || [];
    tabs.push(tabInfo);
    
    chrome.storage.local.set({tabs: tabs})
  });
}

function clearTab() {
  chrome.storage.local.get(['tabs'], function(result) {
    let tabs = result.tabs || [];
    const now = Date.now();
    
    tabs = tabs.filter(tab => {
      if (now - tab.openedAt < 600000) { // 600,000毫秒等于10分钟
        return true;
      } else {
        // 尝试关闭超过10分钟的tab
        chrome.tabs.remove(tab.id, ()=>{if (chrome.runtime.lastError);});
        return false;
      }
    });
    
    chrome.storage.local.set({tabs: tabs})
  });
}







